package com.mike.uaa.web;

import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据响应
 *
 * @author z zhang
 */
public class ApiResponse<T> implements DataResponse {

    private static final long serialVersionUID = 7273085408208781818L;

    private static final Logger log = LoggerFactory.getLogger(ApiResponse.class);

    private final Integer state;

    private final String message;
    @Getter
    private transient T data;


    @Override
    public Integer getStatus() {
        return this.state;
    }

    @Override
    public String getMessage() {
        return this.message;
    }

    public ApiResponse(DataResponse dataResponse) {
        Checker.checked(dataResponse);
        this.state = dataResponse.getStatus();
        this.message = dataResponse.getMessage();
    }

    public ApiResponse(DataResponse dataResponse, T data) {
        Checker.checked(dataResponse, data);
        this.state = dataResponse.getStatus();
        this.message = dataResponse.getMessage();
        this.data = data;
    }

    public ApiResponse(Integer state, String message) {
        Checker.checked(state, message);
        this.state = state;
        this.message = message;
    }

    public ApiResponse(Integer state, String message, T data) {
        Checker.checked(state, message, data);
        this.state = state;
        this.message = message;
        this.data = data;
    }

    public boolean isSuccess() {
        return this.state != null && this.state == 0;
    }

    public boolean isFailure() {
        return !isSuccess();
    }

    public abstract static class Checker {

        private Checker() {
        }

        public static void checked(Integer state) {
            if (null == state) {
                throw new IllegalArgumentException("state cannot be empty.");
            }
        }

        public static void checked(Integer state, String message) {

            checked(state);

            if (null == message) {
                throw new IllegalArgumentException("message cannot be empty.");
            }
        }

        public static void checked(Integer state, String message, Object data) {

            checked(state, message);

            if (null == data) {
                log.debug("response data cannot be empty.");
            }
        }

        public static void checked(DataResponse dataResponse) {
            checked(dataResponse.getStatus(), dataResponse.getMessage());
        }

        public static void checked(DataResponse dataResponse, Object data) {
            checked(dataResponse.getStatus(), dataResponse.getMessage(), data);
        }
    }
}
